﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

#if NETFRAMEWORK
using Fiddler;
#endif

namespace PddHelper.Framework
{
    public class DaiLiHelper1
    {
        //private static readonly Lazy<DaiLiHelper> lazy = new Lazy<DaiLiHelper>(() => new DaiLiHelper());

        //public static DaiLiHelper Instance { get { return lazy.Value; } }


#if NETFRAMEWORK
        int port = 10091;
        public bool Status = false;

        /// <summary>
        /// 微信解析后 回调事件
        /// </summary>
        /// <param name="html"></param>
        public delegate void BeforeResponse(string html);
        // 定义事件
        public event BeforeResponse OnBeforeResponse;

        public DaiLiHelper1()
        {
            port = new Random().Next(10000, 20000);  
        }

        /// <summary>
        /// 启动代理
        /// </summary>
        public void Register()
        {
            if (!CertMaker.rootCertExists())
            {
                if (CertMaker.createRootCert())//创建根证书并添加到受信任的根证书存储中
                {
                    CertMaker.trustRootCert();
                    Status = true;
                }
            }
        }

        public void Start()
        {
            FiddlerCoreStartupSettings settings = new FiddlerCoreStartupSettingsBuilder().RegisterAsSystemProxy().DecryptSSL().ListenOnPort((ushort)port).Build();
            FiddlerApplication.Startup(settings);
            // 注册 BeforeResponse 事件
            FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;
        }

        /// <summary>
        /// 关闭代理
        /// </summary>
        public void Stop()
        {
            FiddlerApplication.Shutdown();
            Status = false;
        }
        private void FiddlerApplication_BeforeResponse(Session oSession)
        {
            // 获取请求返回的数据
            var sessionString = oSession.GetResponseBodyAsString();

            //Console.WriteLine(oSession.fullUrl);
            //Tools.FileWrite("d:\\url.txt", oSession.fullUrl + "\n", true);
            if (oSession.fullUrl.Contains("/goods.html?goods_id=") || oSession.fullUrl.Contains("/goods2.html?goods_id="))
            {
                var html = oSession.GetResponseBodyAsString();
                //Tools.FileWrite("d:\\1.txt", html, true);
                OnBeforeResponse(html);
            }
        }
#endif
    }
}